package com.sanmao5.wecom.api.token;

import com.sanmao5.wecom.cache.WeComTokenCacheable;
import com.sanmao5.wecom.exception.WeComException;
import com.sanmao5.wecom.object.AgentDetail;
import com.sanmao5.wecom.object.resp.AccessTokenResp;
import com.sanmao5.wecom.util.http.HttpUtil;
import com.sanmao5.wecom.util.json.JsonUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static com.sanmao5.wecom.constants.ReqParamConst.CORP_ID;
import static com.sanmao5.wecom.constants.ReqParamConst.CORP_SECRET;
import static com.sanmao5.wecom.constants.UrlConstant.GET_ACCESS_TOKEN;

/**
 * 访问令牌 API
 *
 * @author 黄侯淳
 * @since JDK 1.8
 */
@Slf4j
public class AccessTokenApi extends AbstractTokenApi {

    /**
     * 构造器
     *
     * @param wecomTokenCacheable 访问令牌缓存
     * @param agentDetail         应用详情
     */
    public AccessTokenApi(WeComTokenCacheable wecomTokenCacheable, AgentDetail agentDetail) {
        super(wecomTokenCacheable, agentDetail);
    }

    @Override
    protected String doGetToken(AgentDetail agentDetail) {
        List<Pair<String, String>> reqParams = new LinkedList<>();
        reqParams.add(new Pair<>(CORP_ID, agentDetail.getCorpId()));
        reqParams.add(new Pair<>(CORP_SECRET, agentDetail.getSecret()));
        Map<String, String> reqHeader = new HashMap<>();
        try {
            AccessTokenResp resp = JsonUtils.parseObject(HttpUtil.get(GET_ACCESS_TOKEN, reqParams, reqHeader), AccessTokenResp.class);
            if (resp == null || resp.isError()) {
                String errorMsg = resp == null ? "token response is null" : resp.getErrmsg();
                throw new WeComException("failed to obtain access token,reason: " + errorMsg);
            }
            return resp.getToken();
        } catch (Exception e) {
            throw new WeComException("failed to obtain access token,reason: " + e.getMessage());
        }
    }
}
